package com.youka.bussiness.common.filter;

import com.youka.bussiness.common.base.BaseException;
import com.youka.bussiness.common.bean.CommonConst;
import com.youka.bussiness.common.utils.SessionContext;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Component
@Setter
@Getter
@Slf4j
@ConfigurationProperties("auth.skip.url")
public class SessionHandler implements HandlerInterceptor {

    private String[] skipAuthUrls;


    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        //校验那些接口需要校验token
        String url = request.getRequestURI();
        Boolean isNotAuth = null != skipAuthUrls && Arrays.asList(skipAuthUrls).contains(url);

        String token = request.getHeader(CommonConst.HEAD_TOKEN);

        //需要验证token
        if (!isNotAuth) {
            if (StringUtils.isNotBlank(token)) {
                throw new BaseException("250", "请重新登录");
            }
            //放入线程上下文
            SessionContext.setCurrentToken("token", SessionContext.getCurrentToken(token));
        }

        return true;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
